package com.nhim.cms.dao;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceException;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.jpa.JpaCallback;
import org.springframework.stereotype.Repository;

import com.nhim.cms.domain.CustomWidgetInstance;
import com.nhim.core.dao.CoreDAO;

/**
 * A data access object (DAO) providing persistence and search support for
 * ContentType entities. Transaction control of the save(), update() and
 * delete() operations can directly support Spring container-managed
 * transactions or they can be augmented to handle user-managed Spring
 * transactions. Each of these methods provides additional information for how
 * to configure it for the desired type of transaction control.
 * 
 * @see .CustomWidgetInstance
 * @author Huy Lieu Ta
 */
@Repository
public class CustomWidgetInstanceDAO extends CoreDAO<Integer, CustomWidgetInstance> implements ICustomWidgetInstanceDAO
{
	
	// property constants
	public static final String DESCRIPTION = "description";
	public static final String NAME = "name";

	@Autowired
	EntityManagerFactory entityManagerFactory;

	@PostConstruct
	public void init() {
		super.setEntityManagerFactory(entityManagerFactory);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<CustomWidgetInstance> getByCustomWidgetId(
			final Integer customWidgetId) {
		try {
			final String queryString = "select model from CustomWidgetInstance model where model.customWidget.id = :propertyValue";
			return getJpaTemplate().executeFind(
					new JpaCallback<List<CustomWidgetInstance>>() {

						@Override
						public List<CustomWidgetInstance> doInJpa(EntityManager em)
								throws PersistenceException {
							Query query = em.createQuery(queryString);
							query.setParameter("propertyValue", customWidgetId);
							return query.getResultList();

						}
					});
		} catch (RuntimeException re) {
			logger.error(
					"getByCustomWidgetId: "
							+ customWidgetId + "failed", re);
			throw re;
		}

	}
	
	public static CustomWidgetInstanceDAO getFromApplicationContext(ApplicationContext ctx) {
		return (CustomWidgetInstanceDAO) ctx.getBean(CustomWidgetInstanceDAO.class);
	}
}
